﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Matlus.FederatedIdentity;
using System.Configuration;
using DTO;
using BLL;
using GUI.Common;
public partial class OAuth_oAuth_Default : System.Web.UI.Page
{
    private string realm = null;
    private string provider;

    #region protected void Page_Load(object sender, EventArgs e)
    protected void Page_Load(object sender, EventArgs e)
    {
        realm = Request.Url.Scheme + "://" + Request.Url.DnsSafeHost + Request.ApplicationPath;

        if (!IsPostBack)
        {
            if (!String.IsNullOrEmpty(Request.PathInfo))
            {

                if (Request.PathInfo.StartsWith("/requestToken"))
                    MakeRequestForToken();
                else if (Request.PathInfo.StartsWith("/authorizeToken"))
                    HandleAuthorizeTokenResponse();
            }
        }
    }
    #endregion

    #region private void MakeRequestForToken()
    /// <summary>
    /// Step 1: Get a Request Token
    /// </summary>
    private void MakeRequestForToken()
    {

        string consumerKey = "355007539375.apps.googleusercontent.com";
        string consumerSecret = "GOEzwYDSwytu7llRN6Fceu1Q";
        string requestTokenEndpoint = null;
        string requestTokenCallback = null;
        string authorizeTokenUrl = null;

        if (Request.PathInfo == "/requestToken/google/")
        {
            consumerKey = "653157390646.apps.googleusercontent.com";
            consumerSecret = "97Ok2swzAGj-2jm66b30WK2k";
            // Google requires an additional "scope" parameter that identifies one of the google applications
            requestTokenEndpoint = "https://www.google.com/accounts/OAuthGetRequestToken?scope=https://www.googleapis.com/auth/userinfo#email";
            // GetRouteableUrlFromRelativeUrl();

            string _diachi = ConfigurationManager.AppSettings["DiaChi"];

            requestTokenCallback = _diachi + "oAuth/default.aspx/authorizeToken/google/";
            authorizeTokenUrl = "https://www.google.com/accounts/OAuthAuthorizeToken";
        }
        else if (Request.PathInfo == "/requestToken/twitter/")
        {
            consumerKey = "";
            consumerSecret = "";
            requestTokenEndpoint = "https://api.twitter.com/oauth/request_token";
            requestTokenCallback = GetRouteableUrlFromRelativeUrl("oAuth/default.aspx/authorizeToken/twitter/");
            authorizeTokenUrl = "https://api.twitter.com/oauth/authorize";
        }
        else if (Request.PathInfo == "/requestToken/yahoo/")
        {
            consumerKey = "";
            consumerSecret = "";
            requestTokenEndpoint = "https://api.login.yahoo.com/oauth/v2/get_request_token";
            requestTokenCallback = GetRouteableUrlFromRelativeUrl("oAuth/default.aspx/authorizeToken/yahoo/");
            authorizeTokenUrl = "https://api.login.yahoo.com/oauth/v2/request_auth";
        }
        else if (Request.PathInfo == "/requestToken/vimeo/")
        {
            consumerKey = "";
            consumerSecret = "";
            requestTokenEndpoint = "http://vimeo.com/oauth/request_token";
            requestTokenCallback = GetRouteableUrlFromRelativeUrl("oAuth/default.aspx/authorizeToken/vimeo/");
            authorizeTokenUrl = "http://vimeo.com/oauth/authorize";
        }

        if (String.IsNullOrEmpty(consumerKey) || String.IsNullOrEmpty(consumerSecret))
            throw new ArgumentException("Please set up your consumer key and consumer secret for the selected provider", "consumerKey or consumerSecret");

        // Step 1: Make the call to request a token
        var oAuthConsumer = new OAuthConsumer();
        var requestToken = oAuthConsumer.GetOAuthRequestToken(requestTokenEndpoint, realm, consumerKey, consumerSecret, requestTokenCallback);
        PersistRequestToken(requestToken);

        // Step 2: Make a the call to authorize the request token
        Response.Redirect(authorizeTokenUrl + "?oauth_token=" + requestToken.Token);
    }
    #endregion

    #region private void HandleAuthorizeTokenResponse()
    /// <summary>
    /// Step 3: Exchange the Request Token for an Access Token
    /// </summary>
    private void HandleAuthorizeTokenResponse()
    {
        string consumerKey = null;
        string consumerSecret = null;
        string accessTokenEndpoint = null;
        string token = null;
        string verifier = null;

        if (Request.PathInfo.StartsWith("/authorizeToken/google/"))
        {
            provider = "Google";
            consumerKey = "653157390646.apps.googleusercontent.com";
            consumerSecret = "97Ok2swzAGj-2jm66b30WK2k";
            token = Request.QueryString["oauth_token"];
            verifier = Request.QueryString["oauth_verifier"];
            accessTokenEndpoint = "https://www.google.com/accounts/OAuthGetAccessToken";
        }
        else if (Request.PathInfo.StartsWith("/authorizeToken/twitter/"))
        {
            provider = "Twitter";
            consumerKey = "";
            consumerSecret = "";
            token = Request.QueryString["oauth_token"];
            verifier = Request.QueryString["oauth_verifier"];
            accessTokenEndpoint = "https://api.twitter.com/oauth/access_token";
        }
        else if (Request.PathInfo.StartsWith("/authorizeToken/yahoo/"))
        {
            provider = "Yahoo!";
            consumerKey = "";
            consumerSecret = "";
            token = Request.QueryString["oauth_token"];
            verifier = Request.QueryString["oauth_verifier"];
            accessTokenEndpoint = "https://api.login.yahoo.com/oauth/v2/get_token";
        }
        else if (Request.PathInfo.StartsWith("/authorizeToken/vimeo/"))
        {
            provider = "Vimeo";
            consumerKey = "";
            consumerSecret = "";
            token = Request.QueryString["oauth_token"];
            verifier = Request.QueryString["oauth_verifier"];
            accessTokenEndpoint = "http://vimeo.com/oauth/access_token";
        }

        if (String.IsNullOrEmpty(consumerKey) || String.IsNullOrEmpty(consumerSecret))
            throw new ArgumentException("Please set up your consumer key and consumer secret for the selected provider", "consumerKey or consumerSecret");

        // Exchange the Request Token for an Access Token
        var oAuthConsumer = new OAuthConsumer();
        var accessToken = oAuthConsumer.GetOAuthAccessToken(accessTokenEndpoint, realm, consumerKey, consumerSecret, token, verifier, GetRequesttoken().TokenSecret);
        // Dòng code này lấy email của người đăng nhập
        var responseText = oAuthConsumer.GetUserInfo("https://www.googleapis.com/userinfo/email", realm, consumerKey, consumerSecret, accessToken.Token, accessToken.TokenSecret);


        //-------------------------------------------------------------------------
        string _diachi = ConfigurationManager.AppSettings["DiaChi"];
        //requestTokenCallback = _diachi + "DangNhap.aspx/authorizeToken/google/";
        // Server trả về username và token
        //        // Kiểm tra token này đã tồn tại trong database chưa?
        //        //      Nếu chưa thì thêm mới khách hàng 
        //        // Đã có rồi thì ko thêm nữa

        try
        {

            string _token = token;
            string _email = CommonClass.GetEmailFromResponse(responseText);

            // Cần kiểm tra trong table NhanVien, nếu có roy thì thôi
            NhanVienDTO _nvDTO = new NhanVienDTO();
            NhanVienBLL _nvBLL = new NhanVienBLL();
            _nvDTO = _nvBLL.GetNhanVienTheoEmail(_email);

            // User đăng nhập ko phải khách hàng
            if (_nvDTO.MaNhanVien != null) // Là nhân viên
            {
                // Gán Session["User"] cho nhân viên
                Session["NhanVien"] = _nvDTO;
            }
            else
            {

                // Kiểm tra trong table KhachHang
                KhachHangDTO _khDTO = new KhachHangDTO();
                KhachHangBLL _khBLL = new KhachHangBLL();
                _khDTO = _khBLL.GetKhachHangTheoEmail(_email);
                if (_khDTO.MaKhachHang != null) // User đăng nhập là khách hàng cũ
                {
                    // Khách hàng thông số
                    // Gán Session["User"] cho khách hàng
                    Session["KhachHang"] = _khDTO;
                    // Khách hàng cũ
                }
                else // Khách hàng đăng nhập là khách mới
                {
                    // Thiết lập thông số
                    // Thêm vào database
                    //1. Mã khách hàng
                    //2. Tên kh
                    //3. Giới tính
                    //4. Đại chỉ
                    //5. Email
                    //6. Điện thoại
                    //7. Quyền
                    //8. Token
                    //9. Tình trạng

                    TaoMaSoTuDongBLL _tmtd = new TaoMaSoTuDongBLL();
                    _khDTO.MaKhachHang = _tmtd.TaoMaTuDong("KhachHang");
                    _khDTO.TenKhachHang = "";
                    _khDTO.GioiTinh = 1;
                    _khDTO.DiaChi = "";
                    _khDTO.Email = _email;
                    _khDTO.CMND = "";
                    _khDTO.DienThoai = "";
                    _khDTO.Quyen = 0;
                    _khDTO.Token = _token;
                    _khDTO.TinhTrang = 0;

                    _khBLL.Them(_khDTO);
                    Session["KhachHang"] = _khDTO;
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }

        //--------------------------------------------------------------------------

        // Quay về trang chủ
        Response.Redirect(_diachi + "Default.aspx");

        // Google Only - This method will get the email of the authenticated user
    }
    #endregion

    #region void PersistRequestToken(RequestToken requestToken)
    void PersistRequestToken(RequestToken requestToken)
    {
        Session["RequestToken"] = requestToken;
    }
    #endregion

    #region RequestToken GetRequesttoken()
    RequestToken GetRequesttoken()
    {
        var requestToken = (RequestToken)Session["RequestToken"];
        Session.Remove("RequestToken");
        return requestToken;
    }
    #endregion

    #region string GetRouteableUrlFromRelativeUrl(string relativeUrl)
    string GetRouteableUrlFromRelativeUrl(string relativeUrl)
    {
        var url = HttpContext.Current.Request.Url;
        return url.Scheme + "://" + url.Host + VirtualPathUtility.ToAbsolute("~/" + relativeUrl);
    }
    #endregion
}